<template>
  <div id="app">
    <!-- 只有认证检查完成后才渲染路由 -->
    <router-view v-if="authChecked" />
    <div v-else class="auth-loading">
      <el-icon class="is-loading" size="40">
        <Loading />
      </el-icon>
      <p>正在验证登录状态...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { Loading } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()
const authChecked = ref(false)  // 添加认证检查标志

onMounted(async () => {
  // 只有存在token时才检查认证状态
  if (authStore.token) {
    try {
      console.log('App启动，恢复认证状态...')
      const isValid = await authStore.checkAuth()
      authChecked.value = true

      console.log('认证状态检查完成:', isValid, '当前路由:', router.currentRoute.value.path)

      // 如果当前在登录页且认证成功，重定向到主页
      if (isValid && router.currentRoute.value.path === '/login') {
        console.log('认证成功，重定向到主页')
        router.push('/dashboard')
      }
    } catch (error) {
      console.error('认证状态检查失败:', error)
      authChecked.value = true
    }
  } else {
    console.log('没有token，直接渲染页面')
    authChecked.value = true
  }
})
</script>

<style scoped>
#app {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}

.auth-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  color: #909399;
}

.auth-loading p {
  margin-top: 16px;
  font-size: 14px;
}
</style>
